﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TyNetCoreBlog.Models.Data;
using TyNetCoreBlog.Models.Entities;
using TyNetCoreBlog.Repository.RepositoryBase;

namespace TyNetCoreBlog.Repository
{
    public class CategoryRepository : RepositoryBase<Category, int>, ICategoryRepository
    {
        public CategoryRepository(AppDbContext dbContext):base(dbContext)
        {
        }

        /// <summary>
        /// 重写GetAllAsync，博客数量排序
        /// </summary>
        /// <returns></returns>
        public override Task<IEnumerable<Category>> GetAllAsync()
        {
            return Task.FromResult(DbContext.Set<Category>().Include(x => x.Blogs)
                .OrderByDescending(x => x.Blogs.Count).AsEnumerable());
        }


        /// <summary>
        /// 名称是否存在（仅在创建时用到）
        /// </summary>
        /// <param name="name"></param>
        /// <returns>存在返回true，不存在返回false</returns>
        public bool NameIsExits(string name)
        {
            var cate = DbContext.Set<Category>().Where(x => x.Name == name).FirstOrDefault();
            return cate != null;
        }
    }
}
